import React from 'react';
import { Form, Input, message, Modal, Spin } from 'antd';
import { SelectComDepTree } from '@/pages/Flow/components/Select';

import { addManualGradeRule, editManualGradeRule, getManualGradeRuleDetail } from '../../services';

const formLayout = {
    wrapperCol: { span: 14 },
    labelCol: { span: 6 }
};
const StarRuleModal = ({ form, visible, setVisible, editId, isView, fetchRuleList, companyId }) => {
    const { getFieldDecorator, validateFields, resetFields, setFieldsValue, getFieldValue } = form;
    const [loading, setLoading] = React.useState(false);
    const [detail, setDetail] = React.useState({}); // 为了详情中显示个部门范围，就得维护这么个state

    React.useEffect(() => {
        if (!visible) return;
        const fetchDetail = async () => {
            setLoading(true);
            const result = await getManualGradeRuleDetail(editId);
            setLoading(false);
            const { code, data = { json: {}, scope: [] }, msg } = result;
            if (code === 10000) {
                setDetail(data);
                setFieldsValue({
                    scoreTarget: data.json.scoreTarget,
                    scoreStandard: data.json.scoreStandard,
                    score: data.json.score,
                    scope: data.scope.map(item => ({ value: item.key, label: item.value }))
                });
            } else {
                message.error(msg);
            }
        };
        if (editId) {
            fetchDetail();
        } else {
            resetFields();
        }
    }, [visible]); // 这里用visible而不是editId，因为需要考虑多人编辑同一个id，而不是考虑减少拉取次数

    const handleOk = () => {
        if (isView) {
            setVisible(false);
            return;
        }

        validateFields(async (err, values) => {
            if (err) return;
            const service = editId ? editManualGradeRule : addManualGradeRule;
            const extraParam = editId ? { id: editId } : {};
            const { scoreTarget, score = 1, scope, scoreStandard } = values;
            const params = {
                json: {
                    scoreTarget,
                    scoreStandard,
                    score
                },
                scope: scope.map(item => ({ key: item.value, value: item.label })),
                ...extraParam
            };
            const result = await service(params);
            if (result.code === 10000) {
                message.success('提交成功');
                setVisible(false);
                fetchRuleList();
            } else {
                message.error(result.msg);
            }
        });
    };

    const handleCancel = () => {
        setVisible(false);
    };

    const getModalTitle = () => {
        if (isView) return '详情';
        return editId ? '编辑' : '新增';
    };

    const viewRender = (component, viewHandle) => {
        if (isView) {
            return viewHandle();
        }
        return component;
    };

    const viewModalProps = isView ? { footer: null } : {};

    return (
        <Modal
            title={getModalTitle()}
            visible={visible}
            onOk={handleOk}
            onCancel={handleCancel}
            okText="确定"
            cancelText="取消"
            {...viewModalProps}
        >
            <Spin spinning={loading}>
                <Form {...formLayout}>
                    <Form.Item label="评分指标名称" required>
                        {viewRender(
                            getFieldDecorator('scoreTarget', {
                                rules: [
                                    { required: true, message: '评分指标名称不能为空' },
                                    { max: 20, message: '不能超过20个字符' }
                                ]
                            })(<Input placeholder="请输入评分指标名称" allowClear />),
                            () => getFieldValue('scoreTarget')
                        )}
                    </Form.Item>
                    <Form.Item label="评分星级" required>
                        五星
                    </Form.Item>
                    <Form.Item label="每星分值" required>
                        {/* {getFieldDecorator('score', {
                            initialValue: 1,
                            rules: [{ required: true, message: '每星评分不能为空' }]
                        })(
                            <InputNumber
                                precision={1}
                                placeholder="请输入每星评分"
                                allowClear
                                style={{ width: '100%' }}
                            />
                        )} */}
                        1.0
                    </Form.Item>
                    <Form.Item
                        label="适用部门"
                        required
                        extra={
                            <div>
                                (已选
                                <span style={{ color: 'blue' }}> {(getFieldValue('scope') || []).length} </span>
                                个部门)
                            </div>
                        }
                    >
                        {viewRender(
                            getFieldDecorator('scope', {
                                rules: [
                                    {
                                        validator: (rule, value, callback) => {
                                            if (!value || !value.length) {
                                                callback('适用部门不能为空');
                                            } else {
                                                callback();
                                            }
                                        }
                                    }
                                ]
                            })(
                                <SelectComDepTree
                                    style={{ width: '300px' }}
                                    companyId={companyId}
                                    treeCheckable
                                    placeholder="请选择部门"
                                    showArrow
                                    multiple
                                    labelInValue
                                    {...(isView ? {} : { maxTagCount: 2 })}
                                />
                            ),
                            () => (detail.scope || []).map(item => item.value).join('; ')
                        )}
                    </Form.Item>
                    <Form.Item label="评分指标说明" required>
                        {viewRender(
                            getFieldDecorator('scoreStandard', {
                                rules: [
                                    { required: true, message: '评分指标说明不能为空' },
                                    { max: 2000, message: '不能超过2000字符' }
                                ]
                            })(<Input.TextArea rows="4" placeholder="请输入评分指标说明" />),
                            () => (
                                <div style={{ maxHeight: 150, overflowY: 'auto' }}>
                                    {getFieldValue('scoreStandard')}
                                </div>
                            )
                        )}
                    </Form.Item>
                </Form>
            </Spin>
        </Modal>
    );
};

export default Form.create()(StarRuleModal);
